{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "db68f9ed-b3d6-4722-92da-d23681ceaab2",
   "metadata": {},
   "source": [
    "# Exercise 2\n",
    "\n",
    "\n",
    "## Supervised Learning- Classification Models\n",
    "\n",
    "---\n",
    "\n",
    "## Overview\n",
    "\n",
    "Welcome to this excercise. We are now going to use our new skills to build our supervised learning models that use classification approach.\n",
    "\n",
    "---\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2c8ab178-0eef-4f65-95f3-bbb26c72cda4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "\n",
    "# Manually set the path relative to the py file's location that you want to import\n",
    "func_lib_path = os.path.abspath(os.path.join(os.getcwd(), '../../'))# Add the path to sys.path\n",
    "sys.path.append(func_lib_path)\n",
    "\n",
    "# Now you can import func_lib\n",
    "import func_lib\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "from sklearn.tree import DecisionTreeClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f652fad8-99c3-47d3-8637-b21d9e852d03",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[*********************100%%**********************]  501 of 501 completed\n",
      "\n",
      "1 Failed download:\n",
      "['SW']: YFChartError(\"%ticker%: Data doesn't exist for startDate = 946702800, endDate = 1714536000\")\n"
     ]
    }
   ],
   "source": [
    "# Retrieve historical price data.\n",
    "# - Use the 'createHistPrices()' function from 'func_lib' to get historical price data.\n",
    "# - Assign the result to the variable 'historical_prices'.\n",
    "\n",
    "historical_prices = func_lib.create_hist_prices()\n",
    "\n",
    "# Define the list of momentum periods.\n",
    "# - Create a list containing different time periods for calculating momentum indicators.\n",
    "# - Assign this list to the variable 'list_of_momentums'.\n",
    "\n",
    "list_of_momentums = [1, 5, 15, 20]\n",
    "\n",
    "# Compute returns based on historical prices and momentum periods.\n",
    "# - Use the 'computingReturns()' function from 'func_lib' with 'historical_prices' and 'list_of_momentums' as inputs.\n",
    "# - Assign the result to the variable 'total_returns'.\n",
    "\n",
    "total_returns = func_lib.compute_returns(historical_prices, list_of_momentums)\n",
    "\n",
    "# Remove any rows with missing values from the returns data.\n",
    "# - Use the 'dropna()' method to remove rows with NaN values from 'total_returns'.\n",
    "# - Apply the change in place to modify the DataFrame directly.\n",
    "\n",
    "total_returns.dropna(inplace=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c0a91e8f-367e-42c0-9a48-e232a859d882",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>F_1_d_returns</th>\n",
       "      <th>1_d_returns</th>\n",
       "      <th>5_d_returns</th>\n",
       "      <th>15_d_returns</th>\n",
       "      <th>20_d_returns</th>\n",
       "      <th>F_1_d_returns_Ind</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Ticker</th>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"5\" valign=\"top\">A</th>\n",
       "      <th>2000-02-01</th>\n",
       "      <td>0.077465</td>\n",
       "      <td>0.072710</td>\n",
       "      <td>0.048938</td>\n",
       "      <td>0.029919</td>\n",
       "      <td>-0.013889</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000-02-02</th>\n",
       "      <td>0.016340</td>\n",
       "      <td>0.077465</td>\n",
       "      <td>0.119853</td>\n",
       "      <td>0.125000</td>\n",
       "      <td>0.150376</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000-02-03</th>\n",
       "      <td>-0.019293</td>\n",
       "      <td>0.016340</td>\n",
       "      <td>0.136073</td>\n",
       "      <td>0.166980</td>\n",
       "      <td>0.246493</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000-02-04</th>\n",
       "      <td>0.042623</td>\n",
       "      <td>-0.019293</td>\n",
       "      <td>0.120294</td>\n",
       "      <td>0.127541</td>\n",
       "      <td>0.270833</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000-02-07</th>\n",
       "      <td>-0.006289</td>\n",
       "      <td>0.042623</td>\n",
       "      <td>0.201133</td>\n",
       "      <td>0.162706</td>\n",
       "      <td>0.223077</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                   F_1_d_returns  1_d_returns  5_d_returns  15_d_returns  \\\n",
       "Ticker Date                                                                \n",
       "A      2000-02-01       0.077465     0.072710     0.048938      0.029919   \n",
       "       2000-02-02       0.016340     0.077465     0.119853      0.125000   \n",
       "       2000-02-03      -0.019293     0.016340     0.136073      0.166980   \n",
       "       2000-02-04       0.042623    -0.019293     0.120294      0.127541   \n",
       "       2000-02-07      -0.006289     0.042623     0.201133      0.162706   \n",
       "\n",
       "                   20_d_returns  F_1_d_returns_Ind  \n",
       "Ticker Date                                         \n",
       "A      2000-02-01     -0.013889                  1  \n",
       "       2000-02-02      0.150376                  1  \n",
       "       2000-02-03      0.246493                  0  \n",
       "       2000-02-04      0.270833                  1  \n",
       "       2000-02-07      0.223077                  0  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Convert 'F_1_d_returns' to binary values based on whether they are positive or not.\n",
    "# - Use the 'apply()' function with a lambda expression to create a new column 'F_1_d_returns_Ind'.\n",
    "# - The lambda expression assigns 1 if the value is greater than 0, otherwise assigns 0.\n",
    "\n",
    "total_returns['F_1_d_returns_Ind'] = total_returns['F_1_d_returns'].apply(lambda x: 1 if x > 0 else 0)\n",
    "# Display the updated DataFrame.\n",
    "total_returns.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8f5424f8-bea9-46d6-b2b1-5ae6934180d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2017-01-20 00:00:00\n"
     ]
    }
   ],
   "source": [
    "# Determine the split index for 70% of the dates.\n",
    "# - Extract the unique dates from the index of 'total_returns'.\n",
    "# - Calculate the split date by indexing into the unique dates to get the date corresponding to 70% of the total length of unique dates.\n",
    "# - Assign this date to the variable 'split_date' and display it.\n",
    "\n",
    "unique_dates = total_returns.index.get_level_values('Date').unique()\n",
    "split_date = unique_dates[int(0.7 * len(unique_dates))]\n",
    "print(split_date)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7f011cc5-a9b6-4e57-9bc0-8c4478e6201c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the training set: all data before the split date.\n",
    "# - Use the 'loc[]' indexer to select rows from 'total_returns' where the date in the index is earlier than 'split_date'.\n",
    "# - Assign this subset of data to the variable 'train_data'.\n",
    "\n",
    "train_data = total_returns.loc[total_returns.index.get_level_values('Date') < split_date]\n",
    "\n",
    "# Create the testing set: all data from the split date onwards.\n",
    "# - Use the 'loc[]' indexer to select rows from 'total_returns' where the date in the index is equal to or later than 'split_date'.\n",
    "# - Assign this subset of data to the variable 'test_data'.\n",
    "\n",
    "test_data = total_returns.loc[total_returns.index.get_level_values('Date') >= split_date]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "25b5cac1-451f-4ddf-91c8-9d2827cd39bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract the target variable for testing.\n",
    "# - Select the 'F_1_d_returns' column from the 'test_data' DataFrame.\n",
    "# - Assign this column to the variable 'total_returns'.\n",
    "\n",
    "total_returns = test_data['F_1_d_returns']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9a100112-7de7-41a9-aeb8-f9f812c68603",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the features and target variables.\n",
    "# - Specify the columns to be used as features ('1_d_returns', '5_d_returns', '15_d_returns', '20_d_returns').\n",
    "# - Specify the column to be used as the target variable ('F_1_d_returns_Ind').\n",
    "\n",
    "features = ['1_d_returns', '5_d_returns', '15_d_returns', '20_d_returns']\n",
    "target   = ['F_1_d_returns_Ind']\n",
    "\n",
    "# Split the data into training and testing sets.\n",
    "# - Extract the feature columns from the training data and testing data.\n",
    "# - Extract the target column from the training data and testing data.\n",
    "\n",
    "X_train = train_data[features]\n",
    "X_test  = test_data[features]\n",
    "y_train = train_data[target]\n",
    "y_test  = test_data[target]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3b6913ea-571f-4e7a-9cdd-b7e2c88a2149",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Standardize the features.\n",
    "# - Create an instance of 'StandardScaler' for scaling the features.\n",
    "# - Fit the scaler to the training data and transform both the training and testing feature sets.\n",
    "# - Convert the scaled arrays back to DataFrames with the same index and column names as the original feature sets.\n",
    "\n",
    "scaler = StandardScaler()\n",
    "\n",
    "# Scale the training features\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "# Scale the testing features\n",
    "X_test_scaled  = scaler.transform(X_test)\n",
    "\n",
    "# Convert the scaled arrays back to DataFrames\n",
    "X_train_scaled = pd.DataFrame(X_train_scaled, index=X_train.index, columns=X_train.columns)\n",
    "X_test_scaled  = pd.DataFrame(X_test_scaled, index=X_test.index, columns=X_test.columns)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ddf84714-4fe4-4880-88ab-9f0dfa74491d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-1 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-1 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-1 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-1 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-1 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-1 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-1 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-1 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-1 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-1 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-1 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>DecisionTreeClassifier()</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;DecisionTreeClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.tree.DecisionTreeClassifier.html\">?<span>Documentation for DecisionTreeClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>DecisionTreeClassifier()</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "DecisionTreeClassifier()"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Initialize and train a Decision Tree classifier.\n",
    "# - Create an instance of the DecisionTreeClassifier class.\n",
    "# - Fit the model to the scaled training data and the target values.\n",
    "\n",
    "model = DecisionTreeClassifier()\n",
    "model.fit(X_train_scaled, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "4828df57-416c-43f0-b99c-b24bc83a74f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the model name.\n",
    "# - Set a string variable 'model_name' to identify the Decision Tree model.\n",
    "\n",
    "model_name = 'DecTree'\n",
    "\n",
    "# Make predictions using the trained Decision Tree model.\n",
    "# - Use the 'predict()' method to generate predictions on the scaled test data.\n",
    "# - Convert the predictions into a DataFrame and set the index to match the test data.\n",
    "\n",
    "y_pred = model.predict(X_test_scaled)\n",
    "y_pred_df = pd.DataFrame(y_pred, index=X_test_scaled.index)\n",
    "\n",
    "# Rename the column in the predictions DataFrame to reflect the model name.\n",
    "# - Use 'rename()' to change the column name to 'model_name'.\n",
    "\n",
    "y_pred_df.rename(columns={0: model_name}, inplace=True)\n",
    "\n",
    "# Convert the actual target values into a DataFrame.\n",
    "# - Ensure the DataFrame has the same index as the predictions DataFrame.\n",
    "\n",
    "y_test_df = pd.DataFrame(y_test)\n",
    "\n",
    "# Merge the predicted and actual target values with the original DataFrame.\n",
    "# - Use 'pd.merge()' to combine 'y_pred_df' and 'total_returns' DataFrames based on their indices.\n",
    "\n",
    "y_test_and_pred = pd.merge(y_pred_df, total_returns, left_index=True, right_index=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "5ea1e907-5b59-4d2e-83ba-dfe4b8262e7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define a trading strategy based on logistic regression predictions.\n",
    "# - Create a function 'trading_strategy' that takes the predicted value 'y_pred' as input.\n",
    "# - If the predicted value is greater than 0.5, return 1 (indicating a \"Go long\" signal).\n",
    "# - Otherwise, return 0 (indicating no action or \"Do nothing\").\n",
    "\n",
    "def trading_strategy(y_pred):\n",
    "    if y_pred > 0:\n",
    "        return 1  # Go long\n",
    "    else:\n",
    "        return 0  # Do nothing\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f76b8327-20eb-49b8-84c1-2a0016340cee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 50740 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The CAGR is: 16.05%\n",
      "Sharpe Ratio of Strategy: 0.85\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 15516 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Compute performance metrics based on the predictions and actual returns.\n",
    "# - Use the 'func_lib.compute_BM_Perf()' function to calculate cumulative and calendar returns.\n",
    "# - Pass the DataFrame 'y_test_and_pred' containing the actual and predicted values as an argument.\n",
    "\n",
    "cum_returns, calendar_returns = func_lib.compute_BM_Perf(y_test_and_pred)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "83b115af-3b27-40b2-93f0-2b9cc2fd0db2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 63376 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The CAGR is: 8.63%\n",
      "Sharpe Ratio of Strategy: 0.87\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 18184 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Compute strategy performance metrics.\n",
    "# - Use the 'func_lib.compute_strat_perf()' function to calculate the performance of the trading strategy.\n",
    "# - Pass the following arguments:\n",
    "#   - 'y_test_and_pred': The DataFrame containing actual and predicted values.\n",
    "#   - 'cum_returns': Cumulative returns calculated previously.\n",
    "#   - 'calendar_returns': Calendar returns calculated previously.\n",
    "#   - 'trading_strategy': The function defining the trading strategy based on predictions.\n",
    "#   - 'model_name': The name of the model to include in the performance evaluation.\n",
    "\n",
    "cum_returns, calendar_returns = func_lib.compute_strat_perf(\n",
    "    y_test_and_pred, \n",
    "    cum_returns, \n",
    "    calendar_returns, \n",
    "    trading_strategy, \n",
    "    model_name\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "778fd7b3-dcae-4307-930f-90a3830fde8b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ab0ed24-039d-4216-b81c-b08e7094b1e1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afc481bc-dfc6-46ab-91e8-30d7dcecc813",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
